package main

//传统同步机制
import (
	"fmt"
	"sync"
	"time"
)

//无同步，导致竞争出现
// go run -race atomic.go
type atomicInt1 int
type atomicInt2 struct {
	value int
	lock sync.Mutex
}

func (a *atomicInt1) increament1(){
	*a++
}
func (a *atomicInt1) get1()  int {
	return int(*a)
}

func (a *atomicInt2) increament2() {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.value++
}
func (a *atomicInt2) get2()  int {
	a.lock.Lock()
	defer a.lock.Unlock()
	return a.value
}

func main() {
	//print1()
	print2()
}

func print1(){
	var a atomicInt1
	a.increament1()
	go func() {
		a.increament1()
	}()
	//不加会导致go func还没有执行就退出
	time.Sleep(time.Millisecond)
	fmt.Println(a)
}

func print2(){
	var a atomicInt2
	a.increament2()
	go func() {
		a.increament2()
	}()
	//不加会导致go func还没有执行就退出
	time.Sleep(time.Millisecond)
	fmt.Println(a.get2())
}
